package com.btpj.jetpack.http

import com.btpj.jetpack.BuildConfig
import com.btpj.jetpack.http.interceptor.CommonInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * RetrofitClient
 *
 * @author LTP 2020/7/8
 */
class RetrofitClient private constructor() {

    companion object {
        /** 连接超时时间（s） */
        private const val CONNECT_TIME_OUT = 10
        private const val READ_TIME_OUT = 10

        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { RetrofitClient() }
    }

    private var mRetrofit: Retrofit

    init {
        mRetrofit = Retrofit.Builder()
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://www.wanandroid.com")
            .build()
    }

    private val logInterceptor: HttpLoggingInterceptor
        get() {
            val logInterceptor = HttpLoggingInterceptor()
            logInterceptor.level =
                if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.BASIC
            return logInterceptor
        }

    private val client: OkHttpClient
        get() {
            return OkHttpClient.Builder()
                .addInterceptor(logInterceptor)
                .addInterceptor(CommonInterceptor())
                .connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT.toLong(), TimeUnit.SECONDS)
                .build()
        }

    fun <T> create(service: Class<T>): T {
        return mRetrofit.create(service)
    }
}